<?php
/*
 * @Descripttion: 
 * @version: 1.0
 * @Author: Sam
 * date: 2020-10-20 10:37:46
 * @LastEditors: Sam
 * @LastEditTime: 2022-12-05 15:35:34
 */


namespace app\api\middleware;
use think\facade\Db;
use app\admin\model\User;
use think\Request;
use think\facade\Env;
use app\api\auth\User as UserAuth;


/**
 * API接口token验证中间件
 * Class AuthTokenMiddleware
 * @package app\http\middleware
 */
class TokenMiddleware 
{
    public function handle(Request $request, \Closure $next, bool $force = true)
        {
            $authInfo = null;

            // 从 Authorization 头中获取 Bearer token
            $authHeader = $request->header('Authorization');
            if (!$authHeader || stripos($authHeader, 'Bearer ') !== 0) {
                return json(['code' => 400, 'msg' => '缺少或非法的 Authorization 头']);
            }

            // 提取 Bearer token
            $token = trim(substr($authHeader, 7));

            $jwt = \Jwt::getInstance();
            $jwt->setKey(Env::get('TOKEN_KEY')); // 设置秘钥
            $jwt->setIss(Env::get('TOKEN_ISS')); // 设置签发者

            $info = $jwt->verifyToken($token);
            if (!$info) {
                return json(['code' => 401, 'msg' => 'token验证失败，请重新登录']);
            }

            $user_token = $info['claim']['user_token'] ?? null;
            if (!$user_token) {
                return json(['code' => 400, 'msg' => 'token信息缺失']);
            }

            try {
                $authInfo = Db::name('user')->where('token', $user_token)->find();
                if (!$authInfo) throw new \Exception("无效用户", -4);
            } catch (\Exception $e) {
                return json(['code' => $e->getCode(), 'msg' => $e->getMessage()]);
            }

            // 绑定类
            bind('auth_user', UserAuth::class);
            // 初始化用户信息
            app('auth_user')->withId($authInfo['id'])->withData($authInfo)->setToken($info);

            return $next($request);
        }

}